package com.wzy.alllearning.filter;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

@Order(1)
@WebFilter("/*")
public class TraceIdFilter implements Filter
{
	private static final String TRACE_ID = "traceId";

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
	{
		// 尝试从请求中获取traceId
		String traceId = servletRequest.getParameter(TRACE_ID);
		if (StringUtils.isEmpty(traceId))
		{
			traceId = UUID.randomUUID().toString();
		}

		// MDC 是日志框架提供的一个threadLocal对象，用于往线程中存放变量
		MDC.put(TRACE_ID, traceId);

		// 释放过滤器
		filterChain.doFilter(servletRequest, servletResponse);

	}
}
